package com.drd.dt.modular.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.drd.dt.common.Constant;
import com.drd.dt.common.SuccessResultEnum;
import com.drd.dt.common.tips.Tip;
import com.drd.dt.exception.BizExceptionEnum;
import com.drd.dt.exception.BussinessException;
import com.drd.dt.modular.dao.OrderMapper;
import com.drd.dt.modular.dao.UserMoneyMapper;
import com.drd.dt.modular.dto.GoodsDetailDTO;
import com.drd.dt.modular.entity.Order;
import com.drd.dt.modular.entity.User;
import com.drd.dt.modular.service.WphService;
import com.drd.dt.properties.WPHPropertyConfig;
import com.drd.dt.util.FilterGoodsUtil;
import com.drd.dt.util.ResultUtil;
import com.drd.dt.util.StringUtil;
import com.vip.adp.api.open.service.*;
import com.vip.osp.sdk.context.InvocationContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class WphServiceImpl implements WphService {
    private static final Logger logger = LoggerFactory.getLogger(WphServiceImpl.class);
    private final static String appUrl = "https://gw.vipapis.com/";

    @Autowired
    private GoldCoinServiceImpl goldCoinService;
    @Autowired
    private WPHPropertyConfig wphPropertyConfig;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMoneyServiceImpl testMoneyService;
    @Autowired
    private UserMoneyMapper userMoneyMapper;
    @Autowired
    private FilterGoodsUtil filterGoodsUtil;
    @Autowired
    private FilterGoodsUtil goodsUtil;

    /**
     * 唯品会订单获取
     */
    @Override
    public Tip wphOrder(String start_time, String end_time, Integer wphStatus) throws Exception {
        //订单状态:0-不合格，1-待定，2-已完结，该参数不设置默认代表全部状态
        logger.info("【黑桃省钱wphOrder开始获取唯品会订单...start_time：" + start_time + "，end_time：" + end_time + "，status：" + wphStatus + "】");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer page = 1;
        Boolean isMore = true;
        SimpleDateFormat y_m_d_h_m_s = Constant.y_M_d_H_m_s;
        String our_time = "2019-12-03 18:00:00";//这之前的订单不进库
        while (isMore) {
            OrderResponse wphOrders = getWphOrders(Long.valueOf(start_time), Long.valueOf(end_time), page, wphStatus);//从唯品会查订单数据
            if (null != wphOrders) {
                List<OrderInfo> orderInfoList = wphOrders.getOrderInfoList();
                Integer total = wphOrders.getTotal();
                Integer pageSize = wphOrders.getPageSize();
                Integer size = page * pageSize;
                if (total <= size) {
                    isMore = false;
                }
                page++;
                //遍历唯品会订单列表处理
                for (OrderInfo list : orderInfoList) {
                    //已下单，已付款，已签收，待结算，已结算，已失效
                    String orderStatus = list.getOrderSubStatusName();
                    String order_id = list.getOrderSn();
                    Long orderTime = list.getOrderTime();
                    String create_time = sdf.format(new Date(orderTime));

                    if (y_m_d_h_m_s.parse(create_time).getTime() < y_m_d_h_m_s.parse(our_time).getTime()) {
                        continue;
                    }

                    if (!StringUtils.isEmpty(orderStatus) && (orderStatus.equals("已下单"))) {
                        logger.info("【订单id为：" + order_id + "的订单状态为'"+orderStatus+"'，不进行新增操作...】");
                        continue;
                    }
                    List<OrderDetailInfo> detailList = list.getDetailList();
                    StringBuilder goods_id = new StringBuilder();
                    StringBuilder goods_name = new StringBuilder();
                    Double rake_back = 0.0;
                    Double actual_amount = 0.0;
                    Integer goodsNumber = 0;
                    if (null != detailList && detailList.size() == 1) {
                        goods_id.append(detailList.get(0).getGoodsId());
                        goods_name.append(detailList.get(0).getGoodsName());
                        rake_back = Double.valueOf(detailList.get(0).getCommission());
                        goodsNumber = detailList.get(0).getGoodsCount();
                        actual_amount = Double.valueOf(detailList.get(0).getCommissionTotalCost());
                    } else {
                        for (OrderDetailInfo t : detailList) {
                            goods_id.append("<" + t.getGoodsId() + ">");
                            rake_back += Double.valueOf(t.getCommission());
                            goods_name.append("<" + t.getGoodsName() + ">");
                            goodsNumber += t.getGoodsCount();
                            actual_amount += Double.valueOf(t.getCommissionTotalCost());
                        }
                    }

                    //获取订单
                    Order RepeatOrder = orderMapper.getRepeatOrder(order_id);
                    Integer status = reStatus(orderStatus);
                    if (RepeatOrder != null) {//2,存在的话直接 更新
                        Integer myStatus = RepeatOrder.getStatus();
                        if (myStatus == 2) {
                            Map map = new HashMap();
                            map.put("status", status);
                            map.put("order_id", order_id);
                            if (orderStatus.equals("已结算")) {//已结算既开始返佣
                                Long signTime = list.getSignTime();//签收时间 时间戳 单位毫秒
                                String clear_time = sdf.format(new Date(signTime));
                                logger.info("【黑桃省钱开始更新唯品会订单号为 【" + order_id + "】的订单佣金...】");
//                                goodsUtil.rakeMoneyNew(order_id, rake_back, String.valueOf(goods_id), clear_time, 0.0);//返佣金
                            } else if (myStatus != status) {
                                logger.info("【黑桃省钱开始更新唯品会订单号为 【" + order_id + "】的订单状态...】");
                                orderMapper.updateOrderStatus(map);//更新order表
                                RepeatOrder.setStatus(status);
                                testMoneyService.updateOrderFansRake(RepeatOrder);
                            }
                        }
                    } else {//添加
                        String channel_id = "";
                        String channelTag = list.getChannelTag();
                        Integer user_id = 0;
                        Integer buytype = 0;
                        if (!StringUtils.isEmpty(channelTag) && channelTag.contains("_")) {
                            String[] split = channelTag.split("_");
                            user_id = Integer.valueOf(split[0]);
                            buytype = Integer.valueOf(split[1]);
                        }
                        if (!StringUtils.isEmpty(user_id) && user_id > 0) {
                            Order order = new Order();
                            order.setBuytype(buytype);
                            order.setChannel_id(channel_id);
                            order.setProduct_id(goods_id.toString());
                            order.setProduct_pic_url(detailList.get(0).getGoodsThumb());
                            order.setProduct_name(goods_name.toString());
                            order.setUser_id(user_id);
                            order.setOrder_id(order_id);
                            order.setType(4);
                            order.setStatus(status);
                            order.setUser_rake_back("0");
                            order.setNumber(goodsNumber);
                            order.setActual_amount(String.valueOf(actual_amount));
                            order.setRake_back(String.valueOf(rake_back));
                            order.setCreate_time(create_time);
                            //使用红包
                            Integer redpacket = 0;
                            try {
                                redpacket = goldCoinService.userRedpacket(String.valueOf(user_id));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            order.setRedpacket(redpacket);

                            Map mapuser = new HashMap();
                            mapuser.put("id", user_id);
                            User user = userMoneyMapper.getByUserId(mapuser);
                            double rate = testMoneyService.getRakeBackRatebyUser(user);
                            order.setUser_rake(rate + "");
                            order.setUser_rake_back_yugu(testMoneyService.round(rate * rake_back + ""));
                            orderMapper.insert(order);
                            if (null != user && order != null && rake_back > 0 && !orderStatus.equals("已失效")) {
                                testMoneyService.updateOrderFansRake(user, order);//新增加订单
                            }
                        }
                    }
                }
            }
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage());
    }


    /**
     * 唯品会链接生成购买链接
     *
     * @return
     */
    @Override
    public Tip wphGenerateLink(Integer user_id, String goods_id, Integer buy_type) throws Exception {
        String appKey = wphPropertyConfig.getAppKey();
        String appSecret = wphPropertyConfig.getAppSecret();
        if (StringUtils.isEmpty(user_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }

        UnionUrlServiceHelper.UnionUrlServiceClient client = new UnionUrlServiceHelper.UnionUrlServiceClient();
        InvocationContext invocationContext = InvocationContext.Factory.getInstance();
        invocationContext.setAppKey(appKey);
        invocationContext.setAppSecret(appSecret);
        invocationContext.setAppURL(appUrl);
        String uuid = UUID.randomUUID().toString();
        List<String> url = new ArrayList<>();
        UrlGenResponse urlGenResponse;
        if (StringUtils.isEmpty(goods_id)) {
            String link = orderMapper.getWphLink();//获取唯品会联盟跳转链接
            url.add(link);
            urlGenResponse = client.genByVIPUrl(url, user_id + "_" + buy_type, uuid);
        } else {//商品转链
            url.add(goods_id);
            urlGenResponse = client.genByGoodsId(url, user_id + "_" + buy_type, uuid);
        }
        List<UrlInfo> urlInfoList = urlGenResponse.getUrlInfoList();
        UrlInfo urlInfo = null;
        if (urlInfoList.size() > 0) {
            urlInfo = urlInfoList.get(0);
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), urlInfo);
    }

    /**
     * 唯品会关键词查询商品
     *
     * @return
     */
    @Override
    public Tip wphQuery(Integer page, String keyword, Integer order, String fieldname, Integer user_id) throws Exception {
        JSONArray result = new JSONArray();
        keyword = StringUtil.getKeyword(keyword);
        //fieldname:排序字段：支持price和discount     order:排序：0-正序，1-逆序
        if (StringUtils.isEmpty(keyword)) {keyword = "全部";}
        if (StringUtils.isEmpty(fieldname)) {fieldname = "price";}
        if (StringUtils.isEmpty(order)) {order = 0;}
        Integer pageSize = Constant.PAGE_SIZE_20;
        UnionGoodsServiceHelper.UnionGoodsServiceClient client = new UnionGoodsServiceHelper.UnionGoodsServiceClient();
        InvocationContext invocationContext = InvocationContext.Factory.getInstance();
        String appKey = wphPropertyConfig.getAppKey();
        String appSecret = wphPropertyConfig.getAppSecret();
        invocationContext.setAppKey(appKey);
        invocationContext.setAppSecret(appSecret);
        invocationContext.setAppURL(appUrl);
        QueryGoodsRequest request = new QueryGoodsRequest();
        request.setPage(Integer.valueOf(page));
        request.setPageSize(pageSize);
        String uuid = UUID.randomUUID().toString();
        request.setRequestId(uuid);
        if (!StringUtils.isEmpty(fieldname)) {
            request.setFieldName(fieldname);
        }
        if (!StringUtils.isEmpty(order)) {
            request.setOrder(order);
        }

        List<GoodsInfo> goodsInfoList = new ArrayList<>();
        Boolean flag = true;
        while (flag){
            request.setKeyword(keyword);
            GoodsInfoResponse query = client.query(request);
            goodsInfoList = query.getGoodsInfoList();
            if (null == goodsInfoList || goodsInfoList.size() < 1){
                if (keyword.length() > 5){
                    keyword = keyword.substring(0,keyword.length() - 5);
                }else {
                    flag = false;
                }
            }else {
                flag = false;
            }
        }

        if (null != goodsInfoList) {
            Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);
            goodsInfoList.stream().forEach(t -> {
                GoodsDetailDTO detailDTO = new GoodsDetailDTO();
                detailDTO.setGoodsId(t.getGoodsId());
                detailDTO.setGoodsName(t.getGoodsName());
                detailDTO.setGoodsMainPicture(t.getGoodsMainPicture());
                String vipPrice = t.getVipPrice();//唯品价
                detailDTO.setPrice(vipPrice);
                detailDTO.setPriceAfterCoupon(vipPrice);
                Double commission = Double.valueOf(t.getCommission()) * reback_money.doubleValue();
                Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
                Double upcommission = Double.valueOf(t.getCommission()) * upreback_money.doubleValue();
                detailDTO.setCommission(String.format("%.2f", commission));//佣金金额
                detailDTO.setUpcommission(String.format("%.2f", upcommission));//上一级佣金金额
                Double endPrice = Double.valueOf(vipPrice) - commission;
                detailDTO.setStoreName(t.getBrandName());
                detailDTO.setGoodsDesc(t.getGoodsDesc());
                detailDTO.setType(4);

                //店铺
                StoreInfo storeInfo = t.getStoreInfo();
                detailDTO.setStoreUserId(storeInfo.getStoreId());
                detailDTO.setStoreName(storeInfo.getStoreName());

                Map<String, Object> storeGiveAMark = new HashMap<>();
                storeGiveAMark.put("storeName", detailDTO.getStoreName());
                storeGiveAMark.put("storeUserId", detailDTO.getStoreUserId());
                storeGiveAMark.put("storeIcon", detailDTO.getStoreIcon());
                storeGiveAMark.put("storeURL", detailDTO.getStoreURL());
                detailDTO.setStoreGiveAMark(storeGiveAMark);

                result.add(detailDTO);
            });
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), result);
    }

    /**
     * 唯品会商品详情
     **/
    @Override
    public Tip wphGoodsDetail(String goods_id, Integer user_id, HttpServletRequest request, String deviceT, String app_version) throws Exception {
        GoodsDetailDTO wphGoods = new GoodsDetailDTO();
        if (!StringUtils.isEmpty(deviceT) && Integer.valueOf(deviceT) == 1) {//ios过审版
            wphGoods = filterGoodsUtil.filterIOSVersion(wphGoods, request, app_version);
        }
        if (StringUtils.isEmpty(goods_id)) {
            throw new BussinessException(BizExceptionEnum.PARAM_EMPTY);
        }
        UnionGoodsServiceHelper.UnionGoodsServiceClient client = new UnionGoodsServiceHelper.UnionGoodsServiceClient();
        InvocationContext invocationContext = InvocationContext.Factory.getInstance();
        String appKey = wphPropertyConfig.getAppKey();
        String appSecret = wphPropertyConfig.getAppSecret();
        invocationContext.setAppKey(appKey);
        invocationContext.setAppSecret(appSecret);
        invocationContext.setAppURL(appUrl);
        String uuid = UUID.randomUUID().toString();
        List<String> goodsIdsList = new ArrayList<>();
        goodsIdsList.add(goods_id);
        List<GoodsInfo> byGoodsIds = client.getByGoodsIds(goodsIdsList, uuid);
        if (null != byGoodsIds && byGoodsIds.size() > 0) {
            Double reback_money = testMoneyService.getSelftRakeBackRate(user_id);//平台返佣比例
            GoodsInfo goodsInfo = byGoodsIds.get(0);
            wphGoods.setGoodsId(goodsInfo.getGoodsId());
            String goodsName = goodsInfo.getGoodsName();
            wphGoods.setGoodsName(goodsName);
            wphGoods.setGoodsDesc(goodsInfo.getGoodsDesc());
            String vipPrice = goodsInfo.getVipPrice();
            wphGoods.setPrice(vipPrice);
            wphGoods.setStoreName(goodsInfo.getStoreInfo().getStoreName());
            wphGoods.setGoodsMainPicture(goodsInfo.getGoodsMainPicture());
            wphGoods.setGoodsCarouselPictures(goodsInfo.getGoodsCarouselPictures());
            Double commissionRate = Double.valueOf(goodsInfo.getCommissionRate()) / 100;
            Double commission = Double.valueOf(vipPrice) * commissionRate * reback_money.doubleValue();
            Double upreback_money = testMoneyService.getUpLevelRakeBackRate(reback_money);
            Double upcommission = Double.valueOf(vipPrice) * commissionRate * upreback_money.doubleValue();
            String vipDesc = filterGoodsUtil.vipDesc(upcommission,user_id);
            wphGoods.setVipDesc(vipDesc);
            wphGoods.setCommission(String.format("%.2f", commission));
            wphGoods.setUpcommission(String.format("%.2f", upcommission));
            wphGoods.setPriceAfterCoupon(vipPrice);
            wphGoods.setType(4);
            //店铺
            StoreInfo storeInfo = goodsInfo.getStoreInfo();
            wphGoods.setStoreUserId(storeInfo.getStoreId());
            wphGoods.setStoreName(storeInfo.getStoreName());

            Map<String, Object> storeGiveAMark = new HashMap<>();
            storeGiveAMark.put("storeName", wphGoods.getStoreName());
            storeGiveAMark.put("storeUserId", wphGoods.getStoreUserId());
            storeGiveAMark.put("storeIcon", wphGoods.getStoreIcon());
            storeGiveAMark.put("storeURL", wphGoods.getStoreURL());
            wphGoods.setStoreGiveAMark(storeGiveAMark);

            //相关推荐 根据1级分类名称来查询
            Tip tip = wphQuery(1, goodsInfo.getCat1stName(), 0, "price",user_id);
            wphGoods.setRelatedRecommendation((List<GoodsDetailDTO>) tip.getData());

            //H5URL 商品详情
            wphGoods.setH5Url("");
        }
        return ResultUtil.result(SuccessResultEnum.SUCCESS.getCode(), SuccessResultEnum.SUCCESS.getMessage(), wphGoods);
    }


    /**
     * 订单状态转换
     *
     * @param status
     * @return int
     */
    public Integer reStatus(String status) {
        //已下单，已付款，已签收，待结算，已结算，已失效
        if (status.equals("已下单") || status.equals("已付款") || status.equals("已签收")) {//已经付款
            return 2;
        } else if (status.equals("待结算") || status.equals("已结算")) { //已经结算
            return 1;
        } else {  //失效
            return 4;
        }
    }

    /**
     * 获取唯品会订单
     */
    public OrderResponse getWphOrders(Long startTime, Long endTime, Integer page, Integer status) throws Exception {
        UnionOrderServiceHelper.UnionOrderServiceClient client = new UnionOrderServiceHelper.UnionOrderServiceClient();
        InvocationContext invocationContext = InvocationContext.Factory.getInstance();
        String appKey = wphPropertyConfig.getAppKey();
        String appSecret = wphPropertyConfig.getAppSecret();
        invocationContext.setAppKey(appKey);
        invocationContext.setAppSecret(appSecret);
        invocationContext.setAppURL(appUrl);
        OrderQueryModel orderQueryModel = new OrderQueryModel();
        orderQueryModel.setPage(page);
        if (!StringUtils.isEmpty(status) && status == 2) {//更新时间
            orderQueryModel.setUpdateTimeStart(startTime);
            orderQueryModel.setUpdateTimeEnd(endTime);
        } else {//下单时间
            orderQueryModel.setOrderTimeStart(startTime);
            orderQueryModel.setOrderTimeEnd(endTime);
        }
        String uuid = UUID.randomUUID().toString();
        orderQueryModel.setRequestId(uuid);
        OrderResponse orderResponse = client.orderList(orderQueryModel);
        return orderResponse;
    }

}
